package consumer;

import config.MqConfig;
import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;

import java.util.Properties;
import org.apache.log4j.Logger;
import org.ini4j.Ini;
import org.ini4j.Profile.Section;
import java.io.FileReader;
import java.io.IOException;

/**
 * MQ 接收消息
 */
public class SimpleMQConsumer {

    private static Logger logger = Logger.getLogger(SimpleMQConsumer.class);

    public static void main(String[] args) {
        Ini ini = new Ini();
        try {
            //加载配置文件
            ini.load(new FileReader(MqConfig.config_file));
            Section aliyun_section = ini.get(MqConfig.aliyun_section);
            Section consumer_section = ini.get(MqConfig.consumer_section);

            logger.info("SimpleMQConsumer start");
            Properties consumerProperties = new Properties();
            consumerProperties.setProperty(PropertyKeyConst.AccessKey, aliyun_section.get("ACCESS_KEY"));
            consumerProperties.setProperty(PropertyKeyConst.SecretKey, aliyun_section.get("SECRET_KEY"));
            consumerProperties.setProperty(PropertyKeyConst.NAMESRV_ADDR, aliyun_section.get("NAMESRV_ADDR"));
            consumerProperties.setProperty(PropertyKeyConst.GROUP_ID, consumer_section.get("GROUP_ID"));
            // 设置一个线程消费
            consumerProperties.setProperty(PropertyKeyConst.ConsumeThreadNums,consumer_section.get("ConsumeThreadNums"));
            Consumer consumer = ONSFactory.createConsumer(consumerProperties);
            consumer.subscribe(consumer_section.get("SUB_TOPIC"), consumer_section.get("SUB_TAGS"), new MessageListenerImpl());
            consumer.start();
            System.out.println("Consumer start success.");
            //等待固定时间防止进程退出
            Thread.sleep(200000);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        catch (IOException e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }
}
